import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:gluz/app/data/shop/shop_list_entity.dart';
import 'package:gluz/app/routes/app_pages.dart';
import 'package:gluz/app/utils/toast_util.dart';

import '../../../../../app_session.dart';

class SearchController extends GetxController {
  // 搜索输入控制器
  final TextEditingController searchController = TextEditingController();

  // 搜索历史记录
  final RxList<String> searchHistory = <String>[].obs;

  // 搜索结果
  List<ShopListEntity> searchResults = [];

  // 搜索状态
  final RxBool isSearching = false.obs;
  final RxBool hasSearched = false.obs;

  // 分页相关
  int pageSize = 100;
  int currentPage = 0;
  bool isLoadingMore = false;
  bool hasMoreData = true;
  String? currentSearchKeyword;

  // 获取当前用户ID
  String get _currentUserId {
    final user = app.getUser();
    return user?.id ?? 'anonymous';
  }

  // 获取用户专属的历史记录存储key
  String get _historyKey => 'search_history_$_currentUserId';

  @override
  void onInit() {
    super.onInit();
    _loadSearchHistory();
  }

  @override
  void onClose() {
    searchController.dispose();
    super.onClose();
  }

  // 加载搜索历史
  void _loadSearchHistory() {
    try {
      final box = GetStorage();
      final history = box.read<List>(_historyKey)?.cast<String>() ?? [];
      searchHistory.value = history;
      logger.d('加载用户 $_currentUserId 的搜索历史: $history');
    } catch (e) {
      logger.e('加载搜索历史失败: $e');
      searchHistory.value = [];
    }
  }

  // 保存搜索历史
  void _saveSearchHistory() {
    try {
      final box = GetStorage();
      box.write(_historyKey, searchHistory);
      logger.d('保存用户 $_currentUserId 的搜索历史: $searchHistory');
    } catch (e) {
      logger.e('保存搜索历史失败: $e');
    }
  }

  // 添加搜索历史
  void _addToHistory(String keyword) {
    if (keyword.trim().isEmpty) return;

    // 移除重复项
    searchHistory.remove(keyword.trim());
    // 添加到开头
    searchHistory.insert(0, keyword.trim());
    // 限制历史记录数量
    if (searchHistory.length > 10) {
      searchHistory.removeLast();
    }
    _saveSearchHistory();
  }

  // 执行搜索
  Future<void> performSearch({String? keyword}) async {
    final searchKeyword = keyword ?? searchController.text.trim();
    if (searchKeyword.isEmpty) {
      ToastUtil.show('请输入搜索关键词');
      return;
    }

    // 添加到历史记录
    _addToHistory(searchKeyword);

    // 设置搜索状态
    isSearching.value = true;
    hasSearched.value = true;
    currentSearchKeyword = searchKeyword;

    // 重置分页状态
    currentPage = 0;
    hasMoreData = true;
    isLoadingMore = false;

    await _searchProducts(searchKeyword);
  }

  // 搜索商品
  Future<void> _searchProducts(String keyword) async {
    try {
      Map<String, dynamic> resMap = {};
      List<ShopListEntity>? products = await app.http.request(
        path: '/api/mall/getProductList',
        params: {
          'pageSize': pageSize,
          'pageNum': currentPage,
          'productName': keyword,
        },
        fromJson: (e) {
          resMap = e;
          List listMap = resMap['records'];
          return listMap.map((obj) {
            return ShopListEntity.fromJson(Map<String, dynamic>.from(obj));
          }).toList();
        },
      );
      searchResults = products ?? [];

      // 检查是否还有更多数据
      int total = resMap['total'] ?? 0;
      if (searchResults.length == total) {
        hasMoreData = false;
      }
    } catch (e) {
      ToastUtil.dismiss();
      logger.e('搜索商品失败: $e');
      searchResults = [];
    } finally {
      isSearching.value = false;
      update();
    }
  }

  // 加载更多搜索结果
  Future<void> loadMoreResults() async {
    if (isLoadingMore || !hasMoreData || currentSearchKeyword == null) {
      return;
    }

    isLoadingMore = true;
    currentPage++;

    try {
      Map<String, dynamic> resMap = {};
      List<ShopListEntity>? newProducts = await app.http.request(
        path: '/api/mall/getProductList',
        params: {
          'pageSize': pageSize,
          'pageNum': currentPage,
          'productName': currentSearchKeyword,
        },
        fromJson: (e) {
          resMap = e;
          List listMap = e['records'];
          return listMap.map((obj) {
            return ShopListEntity.fromJson(Map<String, dynamic>.from(obj));
          }).toList();
        },
      );

      int total = resMap['total'] ?? 0;
      if (newProducts != null && searchResults.length < total) {
        searchResults.addAll(newProducts);
      } else {
        hasMoreData = false;
      }
    } catch (e) {
      logger.e('加载更多搜索结果失败: $e');
      currentPage--; // 回退页码
    } finally {
      isLoadingMore = false;
      update();
    }
  }

  // 点击历史记录搜索
  void onHistoryTap(String keyword) {
    searchController.text = keyword;
    performSearch(keyword: keyword);
  }

  // 清除搜索历史
  void clearSearchHistory() {
    searchHistory.clear();
    _saveSearchHistory();
  }

  // 商品点击
  void onProductTap(ShopListEntity product) {
    Get.toNamed(Routes.PRODUCT_DETAIL, arguments: product.id);
  }

  // 返回按钮
  void onBackTap() {
    Get.back();
  }
}
